﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using System.Messaging;
using System.Reflection;
using System.Configuration;

namespace WpsConvert
{
    public class QueenHelper
    {
        public Action<string> Received;

        public void Listen()
        {
            #region 启动消息处理器
            var QueenBasePath = @".\private$\";
            try
            {
                //新建消息循环队列或连接到已有的消息队列
                var path = QueenBasePath + "Word2Html";
                MessageQueue mq;
                if (MessageQueue.Exists(path))
                {
                    mq = new MessageQueue(path);
                }
                else
                {
                    mq = MessageQueue.Create(path);
                }

                mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                mq.ReceiveCompleted += (sender, e) =>
                {
                    Console.WriteLine("Word2Html is Receiving");
                    String body = String.Empty;
                    try
                    {
                        var m = mq.EndReceive(e.AsyncResult);
                        Console.WriteLine("Word2Html is EndReceive");
                        body = m.Body.ToString();

                        Received?.Invoke(body);

                        mq.BeginReceive();
                        Console.WriteLine("Word2Html is BeginReceive");
                    }
                    catch (Exception ex){
                        Console.WriteLine(ex.Message);
                    }
                };
                mq.BeginReceive();
                Console.WriteLine("Word2Html is BeginReceive");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            #endregion
        }

        #region 发送消息
        public static void Send(String queueName, String data)
        {
            var QueenBasePath = @".\private$\";

            //新建消息循环队列或连接到已有的消息队列
            var Path = QueenBasePath + queueName;

            MessageQueue mq;

            if (MessageQueue.Exists(Path))
            {
                mq = new MessageQueue(Path);
            }
            else
            {
                mq = MessageQueue.Create(Path);
            }

            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

            mq.Send(data);
        }
        #endregion
    }
}
